package com.wfh.aigenerator.aop;

import com.wfh.aigenerator.annotation.AuthCheck;
import com.wfh.aigenerator.common.ErrorCode;
import com.wfh.aigenerator.exception.BusinessException;
import com.wfh.aigenerator.model.entity.User;
import com.wfh.aigenerator.model.enums.UserRoleEnum;
import com.wfh.aigenerator.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * @Title: AuthInterceptor
 * @Author wangfenghuan
 * @Package com.wfh.aigenerator.aop
 * @Date 2025/7/28 21:38
 * @description: 权限校验切面类
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 权限校验切面
     * @param joinPoint
     * @param authCheck
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String s = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum enumByValue = UserRoleEnum.getEnumByValue(s);
        if(enumByValue == null){
            return joinPoint.proceed();
        }
        String userRole = loginUser.getUserRole();
        UserRoleEnum enumByValue1 = UserRoleEnum.getEnumByValue(userRole);
        if(enumByValue1 == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        if(UserRoleEnum.ADMIN.equals(enumByValue) && !Objects.equals(UserRoleEnum.getEnumByValue(userRole), UserRoleEnum.ADMIN)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 放行
        return joinPoint.proceed();
    }
}
